package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@RequiredArgsConstructor
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    private final StringRedisTemplate stringRedisTemplate;
    /**
     * 查询所有商铺类型
     * @return 商铺类型列表
     */
    @Override
    public Result queryList() {
        //1.从redis中查询商铺类型缓存
        String key = CACHE_SHOP_TYPE_KEY;
        List<ShopType> shopTypeList = new ArrayList<>();
        List<String> lists = stringRedisTemplate.opsForList().range(key, 0, -1); // 从redis中查询json数据
        //2.判断缓存是否存在
        if (!lists.isEmpty()) {
            //3.存在，直接返回
            for (String s : lists) {
                ShopType shopType = JSONUtil.toBean(s, ShopType.class);
                shopTypeList.add(shopType);
            }
            return Result.ok(shopTypeList);
        }
        //4.不存在，从数据库中查询
        shopTypeList = query().orderByAsc("sort").list();
        //5.不存在，返回错误
        if (shopTypeList.isEmpty()) {
            return Result.fail("店铺不存在");
        }
        //6.存在，写入redis
        for (ShopType shopType : shopTypeList) {
            String jsonStr = JSONUtil.toJsonStr(shopType);
            lists.add(jsonStr);
        }
        stringRedisTemplate.opsForList().rightPushAll(key, lists);
        //7.返回
        return Result.ok(shopTypeList);
    }
}
